﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Windows.Foundation;
using Windows.UI.ApplicationSettings;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;

namespace WindowsStoreApps.Common.Settings
{
    public interface ISettingCommandProvider
    {
        void CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args);
    }

    public class GlobalSettingCommandProvider : ISettingCommandProvider
    {
        private static readonly Lazy<ISettingCommandProvider> _provider =
            new Lazy<ISettingCommandProvider>(
            () =>
            {
                return new GlobalSettingCommandProvider();
            }, true);

        public static ISettingCommandProvider Default
        {
            get
            {
                return _provider.Value;
            }
        }

        private Popup _settingsPopup = null;
        private double _settingsWidth = 346;
        public void CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
        {
            SettingsCommand cmd = new SettingsCommand("sample", "Sound Options", (x) =>
            {
                _settingsPopup = new Popup();
                _settingsPopup.Closed += OnPopupClosed;
                Window.Current.Activated += OnWindowActivated;
                _settingsPopup.IsLightDismissEnabled = true;
                _settingsPopup.Width = _settingsWidth;
                _settingsPopup.Height = Window.Current.Bounds.Height;

                SimpleSettingsNarrow mypane = new SimpleSettingsNarrow();
                mypane.Width = _settingsWidth; // 346
                mypane.Height = Window.Current.Bounds.Height;

                _settingsPopup.Child = mypane;
                _settingsPopup.SetValue(Canvas.LeftProperty, Window.Current.Bounds.Width - _settingsWidth);
                _settingsPopup.SetValue(Canvas.TopProperty, 0);
                _settingsPopup.IsOpen = true;
            });

            args.Request.ApplicationCommands.Add(cmd);
        }

        private void OnWindowActivated(object sender, Windows.UI.Core.WindowActivatedEventArgs e)
        {
            if (e.WindowActivationState == Windows.UI.Core.CoreWindowActivationState.Deactivated)
            {
                _settingsPopup.IsOpen = false;
            }
        }

        void OnPopupClosed(object sender, object e)
        {
            Window.Current.Activated -= OnWindowActivated;
        }
    }
}
